var FileSystemUtils = (function (FileSystemUtils) {

  FileSystemUtils.createFolder = function(folderPath, destination) {
    return new Promise(function (resolve, reject) {
      var onTaskComplete = function (folderEntry) {
        //console.log("promise resolved with", folderEntry);
        resolve(folderEntry);
      };
      FileSystemUtils.constructEntryName(folderPath, destination).then(
        function (folderName) {
          //console.log("constructed unique  folderName:", folderName)
          destination.getDirectory(folderName, {create: true, exclusive: true},
            function (folderEntry) {
              onTaskComplete(folderEntry);
          });
      });
    });
  };

  FileSystemUtils.createFile = function(destinationFileName, destination, size) {
    return new Promise(function (resolve, reject) {
      destination.getFile(destinationFileName, {create : true, exclusive : true},
        function (fileEntry) {
          fileEntry.createWriter(function (fileWriter) {
            fileWriter.seek(fileWriter.length);
            fileWriter.truncate(size);
            fileWriter.onwrite = function (event) {
              resolve(fileEntry);
            };
            fileWriter.onerror = reject;
          }, reject);
        }, reject);
    });
  };
  
  FileSystemUtils.isFolder = function (remoteEntry) {
    if (remoteEntry[remoteEntry.length -1] == "/") {
      return true;
    }
    return false;
  };

  FileSystemUtils.entryExists = function(entryName, dirContent, isDir) {
    for (var i = 0; i < dirContent.length; i++) {
      if(dirContent[i].name == entryName && dirContent[i].isDirectory == isDir) {
        return true;
      }
    }
    return false;
  };

  FileSystemUtils.getNameFromPath = function(path) {
    // the full path of a folder will always end with a backslash
    if (path[path.length-1] == "/") {
      path = path.slice(0, path.length-1);
    }
    // get the full entry name following the last backslash
    var entryNameIndex = path.lastIndexOf("/"), fullEntryName;
    if (entryNameIndex == -1) {
      fullEntryName = path;
    }
    else {
      fullEntryName = path.slice(entryNameIndex+1);
    }
    return fullEntryName;
  };

  FileSystemUtils.seperateFileExtention = function(fullEntryName) {
    var fileExtentionIndex = fullEntryName.lastIndexOf("."), entryName,
        fileExtention = "";
    if (fileExtentionIndex == -1) {
      entryName = fullEntryName;
    }
    else {
      fileExtention = fullEntryName.slice(fileExtentionIndex);
      entryName = fullEntryName.slice(0, fileExtentionIndex);
    }
    return {"name": entryName, "extention": fileExtention};
  };

  FileSystemUtils.constructEntryName = function(entryPath, destination) {
    var isDir = false, entryName, fileExtention = "", constructedName;
    // the full path of a folder will always end with a backslash
    if (entryPath[entryPath.length-1] == "/") {
      isDir = true;
      entryPath = entryPath.slice(0, entryPath.length-1);
    }
    var fullEntryName = FileSystemUtils.getNameFromPath(entryPath);
    // if it's a file separate the fileExtention from the fileName
    if (!isDir) {
      var nameAndExtention = FileSystemUtils.seperateFileExtention(fullEntryName);
      entryName = nameAndExtention.name;
      fileExtention = nameAndExtention.extention;
    }
    else {
      entryName = fullEntryName;
    }
    constructedName = fullEntryName;
    return FileSystemUtils.getLocalDirContents(destination).then(function (dirContent) {
        var i = 1;
        while (FileSystemUtils.entryExists(constructedName, dirContent, isDir)) {
          constructedName = entryName + "(" + i + ")" + fileExtention;
          i++;
        }
        return constructedName;
    });
  };

  FileSystemUtils.getLocalDirContents = function(entry) {
    return new Promise(function (resolve, reject) {
      var DirectoryLister = entry.createReader(); //creates a Directory Reader object for listing contents of a directory
      DirectoryLister.readEntries(fetchEntries);
      var list = [];
      function fetchEntries (entries) {
          //once all entries have been returend by readEntries() it produces an empty array
          //the entries produced by readEntries must not include the directory itself "." or its parent ".."
          if (entries.length === 0) {
              resolve(list);
          }
          else {
              for ( var i = 0; i < entries.length; i++) {
                  list.push(entries[i]);
              }
              DirectoryLister.readEntries(fetchEntries); //keep calling readEntries() until we get an empty array
          }
      }
    });
  };
  
  return FileSystemUtils;

}(FileSystemUtils || {}));

